<template>
  <view :style="{'padding':'20rpx','display':'flex','flexDirection':item.me?'row-reverse':'row','textAlign':item.me?'right':'left'}">
    <image v-if="!item.withdraw" class="chat-icon" :src="item.avatar" mode="aspectFill"/>
    <view>
      <view v-if="item.withdraw" class="chat-text-style" :style="[{justifyContent:item.me?'flex-end':'flex-start',margin:'0 15rpx'}]">
        <view :style="{'color':'#000000','backgroundColor':'transparent','fontSize':'30rpx'}" class="chat-text-container">
          {{ item.me ? '你撤回了一条消息' : '对方撤回了一条消息' }}
        </view>
      </view>
      <view v-else @longpress="longpress" :id="'msg-'+item.id" style="margin: 0 15rpx">
        <view v-if="item.type==='image'" @tap="previewImage(item.url)">
          <image lazy-load :src="item.url"
                 :style="{'width': item.width+'px','height': item.height+'px','borderRadius':'6%'}"/>
        </view>
        <view v-else-if="item.type==='video'" @click="playVideo(item)" style="position: relative">
          <view style="left:40%;top:40%;position: absolute;z-index: 999;">
            <image style="width: 60rpx;height: 60rpx" :src="images.play"></image>
          </view>
          <image lazy-load :src="item.cover"
                 :style="{'width': item.width+'px','height': item.height+'px','borderRadius':'6%'}"/>
        </view>
        <view v-else-if="item.type==='file'" @tap="downloadFile(item)">
          <view style="display: flex;width: 420rpx" class="chat-text-container">
            <view>
              <view class="u-line-1" style="width: 300rpx;font-size: 28rpx;">{{ item.fileName }}
              </view>
              <view class="u-type-info" style="font-size: 25rpx;margin-top: 5%"> {{ (item.size / 1024).toFixed(0) }}KB
              </view>
            </view>
            <view>
              <image style="width: 100rpx;height: 100rpx" :src="getFileIcon(item)"/>
            </view>
          </view>
        </view>
        <view v-else-if="item.type==='location'">
          <view @tap="openLocation(item)">
            <view :style="{'backgroundColor':'#FFFFFF','color':'#000000'}"
                  class="chat-text-container">
              <view style="width: 400rpx">
                <view style="font-size: 28rpx" class="u-line-1">{{ item.content }}</view>
                <view style="font-size: 25rpx;margin-top: 1%;color:#303133" class="u-type-info">{{
                    item.address
                  }}
                </view>
              </view>
              <map style="width: 400rpx;height: 200rpx" :markers="markers(item)" id="map" @tap="openLocation(item)"
                   :enable-zoom="false" :enable-scroll="false"
                   :longitude="Number(item.lng)"
                   :latitude="Number(item.lat)"
                   :scale="scale"/>
            </view>
          </view>
        </view>
        <view v-else class="chat-text-style" :style="[{justifyContent:item.me?'flex-end':'flex-start'}]">
          <view
              :style="{'color':item.me?'#FFFFFF':'#000000','backgroundColor':item.me?'#18b566':'#FFFFFF','fontSize':'30rpx'}"
              class="chat-text-container">
            {{ item.content }}
          </view>
        </view>
      </view>
      <view class="u-type-info time">{{ formatDateTime(item.createTime) }}</view>
    </view>
  </view>

</template>

<script>
import images from '@/utils/images'
import {previewFile, toast} from "@/utils/common";

export default {
  name: "chat-item",
  props: {
    item: {
      type: Object,
      default: function () {
        return {
          createTime: '',
          avatar: '',
          username: '',
          content: '',
          me: false
        }
      }
    }
  },
  data() {
    return {
      images,
      scale: 18,
    };
  },
  methods: {
    getFileIcon(msg) {
      if (this.getFileType(msg.url) == 'word') {
        return images.word
      } else if (this.getFileType(msg.url) == 'excel') {
        return images.excel
      } else if (this.getFileType(msg.url) == 'ppt') {
        return images.ppt
      } else if (this.getFileType(msg.url) == 'pdf') {
        return images.pdf
      } else (this.getFileType(msg.url) == 'unknown')
      {
        return images.unknow_file
      }
    },
    longpress(e) {
      uni.createSelectorQuery().in(this).select("#msg-" + this.item.id).boundingClientRect((res) => {
        let data = {}
        data.msg = this.item
        data.node = res
        this.$emit('long', data)
      }).exec();
    },
    playVideo(msg) {
      this.$emit("play", msg)
    },
    markers(e) {
      let point = []
      point.push({
        id: 1,
        width: uni.upx2px(40),
        height: uni.upx2px(46),
        latitude: Number(e.lat),
        longitude: Number(e.lng),
        iconPath: images.marker
      })
      return point
    },
    getFileType(fileName = '') {
      const flieArr = fileName.split('.');
      let suffix = flieArr[flieArr.length - 1];
      if (!suffix) return '';
      suffix = suffix.toLocaleLowerCase();
      const ppt = ['ppt', 'pptx'];
      if (ppt.includes(suffix)) return 'ppt';
      const word = ['doc', 'docx'];
      if (word.includes(suffix)) return 'word';
      const excel = ['xls', 'xlsx'];
      if (excel.includes(suffix)) return 'excel';
      const pdf = ['pdf'];
      if (pdf.includes(suffix)) return 'pdf';
      return 'unknown';
    },
    openLocation(e) {
      uni.openLocation({
        latitude: Number(e.lat),
        longitude: Number(e.lng),
        scale: 12,
        name: e.content,
        complete: function (res) {
          console.log(res)
        }
      })
    },
    // handleClick() {
    //   let videoContext = uni.createVideoContext('video', this)
    //   videoContext.requestFullScreen()
    // },
    // fullScreenChange(e) {
    //   if (!e.detail.fullScreen) {
    //     uni.createVideoContext('video', this).pause();
    //   }
    // },
    downloadFile(e) {
      if (this.getFileType(e.url) === 'unknown') {
        toast("该文件类型不支持打开")
      } else {
        previewFile(e.url)
      }
    },
    previewImage(url) {
      uni.previewImage({
        current: 0,
        urls: [url]
      });
    },
    getWeek(date) {
      const currentDate = new Date(date);
      currentDate.setHours(0, 0, 0, 0);
      currentDate.setDate(currentDate.getDate() + 4 - (currentDate.getDay() || 7));
      const yearStart = new Date(currentDate.getFullYear(), 0, 1);
      const weekNumber = Math.ceil((((currentDate - yearStart) / 86400000) + 1) / 7);
      return weekNumber;
    },
    isYesterday(inputDate, currentDate) {
      const oneDayInMilliseconds = 24 * 60 * 60 * 1000; // One day in milliseconds
      const yesterday = new Date(currentDate - oneDayInMilliseconds);
      return inputDate.toDateString() === yesterday.toDateString();
    },
    formatDateTime(dateTimeString) {
      const inputDate = new Date(dateTimeString);
      const currentDate = new Date();
      const daysOfWeek = ["日", "一", "二", "三", "四", "五", "六"];
      if (inputDate.toDateString() === currentDate.toDateString()) {
        // 如果是今天
        return `${inputDate.getHours().toString().padStart(2, "0")}:${inputDate.getMinutes().toString().padStart(2, "0")}`;
      } else if (this.isYesterday(inputDate, currentDate)) {
        // 如果是昨天
        return `昨天 ${inputDate.getHours().toString().padStart(2, "0")}:${inputDate.getMinutes().toString().padStart(2, "0")}`;
      } else if (inputDate.getFullYear() === currentDate.getFullYear() && this.getWeek(inputDate) === this.getWeek(currentDate)) {
        // 如果是本周内的某一天
        return `星期${daysOfWeek[inputDate.getDay()]}`;
      } else {
        // 如果不是今天、昨天，也不是本周内的某一天
        const year = inputDate.getFullYear().toString().substr(-2); // 获取年份的最后两位
        const month = (inputDate.getMonth() + 1).toString().padStart(2, "0");
        const day = inputDate.getDate().toString().padStart(2, "0");
        return `${year}/${month}/${day}`;
      }
    },

  }
}
</script>

<style scoped>
.time {
  width: 100%;
  font-size: 22rpx;
  margin-right: 3%;
  padding: 0 30upx;
//height: 30upx; line-height: 30upx; font-size: 22upx; border-radius: 40upx;
}


.chat-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: #FFFFFF;
  margin-top: 12rpx;

}


.chat-text-container {
  box-shadow: 0 0 8px rgba(114, 118, 206, 0.2700);
  text-align: left;
  background-color: #FFFFFF;
  border-radius: 20rpx;
  padding: 10rpx 15rpx;
  margin-top: 10rpx;
  /* #ifndef APP-NVUE */
  max-width: 500rpx;
  /* #endif */
}


.chat-text-style {
  display: flex;
  flex-direction: row;
}
</style>